/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package repository;

/**
 *
 * @author ghufron
 */
import java.io.*;
import java.net.*;

import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class RepoServer {
    // Declaration section:
    // declare a server socket and a client socket for the server
    // declare an input and an output stream

    static  Socket clientSocket = null;
    static  ServerSocket serverSocket = null;

    // This chat server can accept up to 10 clients' connections

    static  clientThread t[] = new clientThread[10];

    public static void main(String args[]) {

	// The default port

	int port_number=6211;

	if (args.length < 1)
	    {
		System.out.println("Usage: java FileRepositoryServer \n"+
				   "Now using port number="+port_number);
	    } else {
		port_number=Integer.valueOf(args[0]).intValue();
	    }

	// Initialization section:
	// Try to open a server socket on port port_number (default 6211)
	// Note that we can't choose a port less than 1023 if we are not
	// privileged users (root)

        try {
	    serverSocket = new ServerSocket(port_number);
        }
        catch (IOException e)
	    {System.out.println(e);}

	// Create a socket object from the ServerSocket to listen and accept
	// connections.
	// Open input and output streams for this socket will be created in
	// client's thread since every client is served by the server in
	// an individual thread

	while(true){
	    try {
		clientSocket = serverSocket.accept();
		for(int i=0; i<=9; i++){
		    if(t[i]==null)
			{
                            //buat dan atur thread
			    (t[i] = new clientThread(RepoServer.clientSocket,t)).start();
			    break;
			}
		}
                //if(t[0] != null && t[1] != null && t[2] != null && t[3] != null && t[4] != null && t[5] != null && t[6] != null && t[7] != null && t[8] != null && t[9] != null){
                    //System.out.println("Jumlah user yang sedang login telah mencapai 10 orang. Silakan menunggu terlebih dahulu.");
                //}

	    }
	    catch (IOException e) {
		System.out.println(e);}
	}
    }
}

// This client thread opens the input and the output streams for a particular client,
// ask the client's name, informs all the clients currently connected to the
// server about the fact that a new client has joined the chat room,
// and as long as it receive data, echos that data back to all other clients.
// When the client leaves the chat room this thread informs also all the
// clients about that and terminates.

class clientThread extends Thread{

    DataInputStream is = null;
    PrintStream os = null;
    Socket clientSocket = null;
    clientThread t[];

    public clientThread(Socket clientSocket, clientThread[] t){
	this.clientSocket=clientSocket;
        this.t=t;
    }

    public String[] parseUserPass(String userpass){
        String[] hasil = new String[2];
        hasil = userpass.split("[ ]+");
        return hasil;
    }

    public Boolean Login(String username, String password) throws SQLException{
        Boolean hasil = false;
        PenggunaController user = new PenggunaController();
        if(user.isUserExist(username)){
            ResultSet datauser = user.AmbilPengguna(username);
            datauser.next();
            hasil = password.equals(datauser.getString("password"));
        }
        return hasil;
    }

    public void kirimFile(String namafile) throws FileNotFoundException, IOException{
        //System.out.println("Waiting...");

      //Socket sock = servsock.accept();
      //System.out.println("Accepted connection : " + sock);

      // sendfile
      File myFile = new File (namafile);
      byte [] mybytearray  = new byte [(int)myFile.length()];
      FileInputStream fis = new FileInputStream(myFile);
      BufferedInputStream bis = new BufferedInputStream(fis);
      bis.read(mybytearray,0,mybytearray.length);
      OutputStream out = clientSocket.getOutputStream();
      System.out.println("Sending...");
      out.write((int)myFile.length());
      out.write(mybytearray,0,mybytearray.length);
      out.flush();
      //sock.close();
      FileController filcon = new FileController();
      filcon.TambahFileOtomatis(namafile);
    }

    @Override
    public void run()
    {
	String line;
        String request1;
        String request;
        //String[] userpass;
        //String username;
        //String password;
	try{
	    is = new DataInputStream(clientSocket.getInputStream());
	    os = new PrintStream(clientSocket.getOutputStream());
	    //os.println("Enter your name.");
	    request1 = is.readLine();
            //Request login
            if(request1.equalsIgnoreCase("login")){
                os.println("Request login diterima");
                String[] userpass = parseUserPass(is.readLine());
                String username = userpass[0];
                String password = userpass[1];
                try {
                    //Cek validitas login
                    if (Login(username, password)) {
                        os.println("1");
//                        os.println("Selamat datang, " + username + " :))");
                        Boolean berhenti = false;
                        while(!berhenti){
                            request = is.readLine();
                            //Request direktori
                            if(request.equalsIgnoreCase("direktori client")){
                                os.println("Request direktori client diterima");
                                os.println("Silakan kirim direktori file tempat Anda ingin menyimpan repository.");
                                String direktori = is.readLine();
                                os.println("Direktori penyimpanan Anda adalah: " + direktori);
                            }else if(request.equalsIgnoreCase("direktori server")){
                                os.println("Request direktori server diterima");

                                //String direktori = is.readLine();
                                //os.println("Direktori penyimpanan Anda adalah: " + direktori);
                            }else if(request.equalsIgnoreCase("cek")){
                                os.println("Request cek diterima");
                            }else if(request.equalsIgnoreCase("update")){
                                os.println("Request update diterima");
                            }else if(request.equalsIgnoreCase("commit")){
                                os.println("Request commit diterima");
                            }else{
                                os.println("Request tidak diterima.");
                                berhenti = true;
                            }
                        }
                    } else {
                        os.println("0");
                    }
                } catch (SQLException ex) {
                    Logger.getLogger(clientThread.class.getName()).log(Level.SEVERE, null, ex);
                }
            }else{
                os.println("Request tidak diterima. Harus login terlebih dahulu.");
            }

	    //os.println("Hello "+name+" to our chat room.\nTo leave enter /quit in a new line");
	    //for(int i=0; i<=9; i++)
		//if (t[i]!=null && t[i]!=this){}
		    //t[i].os.println("*** A new user "+name+" entered the chat room !!! ***" );
	    /*while (true) {
		line = is.readLine();
                if(line.startsWith("/quit")) break;
		for(int i=0; i<=9; i++)
		    if (t[i]!=null)  t[i].os.println("<"+"> "+line);
	    }*//*
	    for(int i=0; i<=9; i++)
		if (t[i]!=null && t[i]!=this)
		    t[i].os.println("*** The user is leaving the chat room !!! ***" );*/

	    os.println("Sambungan akan diputuskan.");

	    // Clean up:
	    // Set to null the current thread variable such that other client could
	    // be accepted by the server

	    for(int i=0; i<=9; i++)
		if (t[i]==this) t[i]=null;

	    // close the output stream
	    // close the input stream
	    // close the socket

	    is.close();
	    os.close();
	    clientSocket.close();
	}
	catch(IOException e){};
    }
}
